//
//  SSHBookmark.m
//  Communique
//
//  Created by Thomas on 02/07/2008.
//  Copyright 2008 __CompanyName__. All rights reserved.
//

#import "Bookmark.h"
#import "Tunnel.h"

@implementation Bookmark

@synthesize name=_name;
@synthesize server=_server;
@synthesize username=_username;
@synthesize password=_password;
@synthesize port=_port;
@synthesize command=_command;
@synthesize compressed=_compressed;
@synthesize v1Protocol=_v1Protocol;
@synthesize verbose=_verbose;

- (id) init
{
    if (self = [super init])
    {
        _name = @"Untitled";
		_server = @"domain.com";
        _username = @"user";
        _password = @"";
		_command = @"";
		_port = 22;
		_compressed = FALSE;
		_v1Protocol = FALSE;
		_verbose = FALSE;
		_remoteTunnels  = [[NSMutableArray alloc] init];
		_localTunnels  = [[NSMutableArray alloc] init];
		
		// doesn't seem to work!!
		//[self setKeys:[NSArray arrayWithObjects:@"server",@"port",@"username",nil]
		//	triggerChangeNotificationsForDependentKey:@"sshCommand"];
		
    }
    return self;
}

- (NSMutableArray *) remoteTunnels
{
    return _remoteTunnels;
}

- (NSMutableArray *) localTunnels
{
    return _localTunnels;
}

- (void) setLocalTunnels: (NSArray *)newTunnels
{
    if (_localTunnels != newTunnels)
    {
        [_localTunnels autorelease];
        _localTunnels = [[NSMutableArray alloc] initWithArray: newTunnels];
    }
}

- (void) setRemoteTunnels: (NSArray *)newTunnels
{
    if (_remoteTunnels != newTunnels)
    {
        [_remoteTunnels autorelease];
        _remoteTunnels = [[NSMutableArray alloc] initWithArray: newTunnels];
    }
}

- (void) encodeWithCoder: (NSCoder *)coder { 
	[coder encodeObject: _name forKey:@"name"]; 
	[coder encodeObject: _server forKey:@"server"]; 
	[coder encodeInteger: _port forKey:@"port"]; 
	[coder encodeObject: _username forKey:@"username"]; 
	[coder encodeObject: _password forKey:@"password"]; 
	[coder encodeObject: _command forKey:@"command"];
	[coder encodeBool: _compressed forKey:@"compressed"]; 
	[coder encodeBool: _v1Protocol forKey:@"v1Protocol"];  
	[coder encodeBool: _verbose forKey:@"verbose"];  
	[coder encodeObject: [self localTunnels] forKey:@"localTunnels"]; 
	[coder encodeObject: [self remoteTunnels] forKey:@"remoteTunnels"]; 
} 

- (id) initWithCoder: (NSCoder *) coder { 
	if (self = [super init]) { 
		_name =			[coder decodeObjectForKey:@"name"]; 
		_server=		[coder decodeObjectForKey:@"server"]; 
		_port=			[coder decodeIntegerForKey:@"port"]; 
		_username=		[coder decodeObjectForKey:@"username"]; 
		_password=		[coder decodeObjectForKey:@"password"]; 
		_command=		[coder decodeObjectForKey:@"command"];
		_compressed=		[coder decodeBoolForKey:@"compressed"];
		_v1Protocol=	[coder decodeBoolForKey:@"v1Protocol"];
		_verbose=		[coder decodeBoolForKey:@"verbose"];
		[self setLocalTunnels: [coder decodeObjectForKey:@"localTunnels"]];
		[self setRemoteTunnels: [coder decodeObjectForKey:@"remoteTunnels"]];
	} return self; 
}

- (NSString*) sshCommand {
	NSNumber* port = [NSNumber numberWithInt:_port];	
	
	Tunnel *t;
	NSString* nsTunnels = [[NSString alloc] init];
	//NSString* nsRemoteTunnels = [[NSString alloc] init];
  
	NSEnumerator *e = [_localTunnels objectEnumerator ];
    while (t = [ e nextObject ]) {
		nsTunnels = [nsTunnels stringByAppendingString:[t command]];
    }

	// build ssh string
	NSMutableString *sshCommand = [[NSMutableString alloc] initWithString:@"ssh"];
	if (_verbose)
		[sshCommand appendString:@" -v"];
	
	[sshCommand appendFormat:@" -p %@", port];
	
	if ([nsTunnels length]>0)
		[sshCommand appendFormat:@" %@", nsTunnels];
	
	
	[sshCommand appendFormat:@" %@@%@", _username, _server];
	
	if ([_command isNotEqualTo:nil])
		[sshCommand appendFormat:@" %@", _command];
	
	return sshCommand;
}

- (void) launchInTerminal {
	NSWorkspace * ws = [NSWorkspace sharedWorkspace];
	BOOL wasLaunched = [ws launchApplication:@"Terminal"];
	if (wasLaunched)
		NSLog (@"Terminal was launched");
	else
		NSLog (@"Terminal was not launched");	
	
	NSString *sshCommand = [self sshCommand];
	
	[self doTerminalScript:sshCommand];
}

- (int) doTerminalScript: (NSString *)NSutf8Script {
	NSLog (NSutf8Script);
	const char* utf8Script = [NSutf8Script UTF8String]; 
	/*
     * Run a shell script in Terminal.app.
     * (Terminal.app must be running first.)
     */
    char *bundleID = "com.apple.terminal";
    AppleEvent evt, res;
    AEDesc desc;
    OSStatus err;
	
	// Build event
	err = AEBuildAppleEvent(kAECoreSuite, kAEDoScript,
							typeApplicationBundleID,
							bundleID, strlen(bundleID),
							kAutoGenerateReturnID,
							kAnyTransactionID,
							&evt, NULL,
							"'----':utf8(@)", strlen(utf8Script), utf8Script);
	if (err) return err;
	// Send event and check for any Apple Event Manager errors
	err = AESendMessage(&evt, &res, kAEWaitReply, kAEDefaultTimeout);
	AEDisposeDesc(&evt);
	if (err) return err;
	// Check for any application errors
	err = AEGetParamDesc(&res, keyErrorNumber, typeSInt32, &desc);
	AEDisposeDesc(&res);
	if (!err) {
		AEGetDescData(&desc, &err, sizeof(err));
		AEDisposeDesc(&desc);
	} else if (err == errAEDescNotFound)
		err = noErr;
	return err;
}

@end
